<template>
  <el-card style="margin: 15px 0">
    <el-form inline>
      <el-form-item label="用户名:" width="400px">
        <el-input v-model="keyWords" placeholder="搜索用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="!keyWords.length"
          type="primary"
          size="default"
          @click="getUserList"
        >
          搜索
        </el-button>
        <el-button size="default" @click="reset" :loading="resetLoading">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" size="default" @click="addUser">
      添加用户
    </el-button>
    <el-button
      :disabled="!selectDeleteUser.length"
      type="danger"
      size="default"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <el-table
      @selection-change="selectUser"
      v-loading="loading"
      :data="userData"
      border
      style="margin: 15px 0"
    >
      <el-table-column
        type="selection"
        align="center"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="序号"
        width="80px"
        type="index"
        align="center"
      ></el-table-column>
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column
        prop="id"
        label="用户姓名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="用户名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="roleName"
        label="用户角色"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        show-overflow-tooltip
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        show-overflow-tooltip
        label="更新时间"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="350px">
        <template #default="{ row }">
          <el-button @click="setRole(row)" size="default">分配角色</el-button>
          <el-button
            @click="updateUser(row)"
            type="primary"
            icon="Edit"
            size="default"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`确定要删除${row.name}吗?`"
            icon-color="#626e4e"
            icon="Delete"
            width="260"
            @confirm="deleteCurUser(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="default" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 1, 2]"
      :small="true"
      :disabled="!total"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="getUserList"
      @current-change="getUserList"
    />
  </el-card>
  <el-drawer v-model="drawer" @close="cancel">
    <template #header>
      <h4>{{ paramsData.id ? '编辑用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form
        label-width="110px"
        ref="formRef"
        :model="paramsData"
        :rules="rules"
      >
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请输入用户姓名"
            v-model="paramsData.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请输入用户昵称"
            v-model="paramsData.username"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!paramsData.id" label="用户密码" prop="password">
          <el-input
            placeholder="请输入用户密码"
            v-model="paramsData.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="save">确定</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
  <RoleDrawer ref="RoleDrawerRef" />
</template>

<script lang="ts" setup>
import RoleDrawer from './setRole.vue'
import { onMounted, reactive, ref } from 'vue'
import {
  reqUserList,
  reqAddOrUpdateUser,
  reqDeleteCurUser,
  reqDeleteSelectUsers,
} from '@/api/acl/user'
import type { recordsData, ResponseUserList } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'

// vc
const RoleDrawerRef = ref()
// 分配角色
const setRole = (row: recordsData) => {
  RoleDrawerRef.value.showDrawer(row)
}

const formRef = ref()
// 分页器内容
const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(0)
onMounted(() => {
  getUserList()
})
const loading = ref(false)
const userData = ref<recordsData[]>([])
const keyWords = ref('')
const getUserList = async () => {
  loading.value = true
  const res: ResponseUserList = await reqUserList(
    pageNo.value,
    pageSize.value,
    keyWords.value,
  )
  loading.value = false
  userData.value = res.data.records
  total.value = res.data.total
}
const resetLoading = ref(false)
const reset = () => {
  // 重新刷新
  resetLoading.value = true
  keyWords.value = ''
  pageNo.value = 1
  getUserList()
  resetLoading.value = false
}

// 批量删除
const deleteSelectUser = async () => {
  const idsList = selectDeleteUser.value.map((item: any) => item.id)
  const res = await reqDeleteSelectUsers(idsList)
  if (res.code === 200) {
    ElMessage.success('批量删除成功')
    getUserList()
  }
}
// 点击table时,收集选中的列
const selectDeleteUser = ref<any>([])
const selectUser = (val: any) => {
  selectDeleteUser.value = val
}
const deleteCurUser = async (userId: number) => {
  const res = await reqDeleteCurUser(userId)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getUserList()
  }
}

const drawer = ref(false)
const paramsData = reactive<any>({
  username: '',
  name: '',
  password: '',
})
const validatorUsername = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 5) return callBack()
  callBack(new Error('用户姓名至少六位'))
}
const validatorName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 3) return callBack()
  callBack(new Error('用户昵称至少六位'))
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 5) return callBack()
  callBack(new Error('用户密码至少六位'))
}
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
// 添加用户按钮
const addUser = () => {
  drawer.value = true
}
// 更新用户按钮
const updateUser = (row: recordsData) => {
  drawer.value = true
  Object.assign(paramsData, row)
}
const save = async () => {
  await formRef.value.validate()
  try {
    await reqAddOrUpdateUser(paramsData)
    ElMessage.success(paramsData.id ? '编辑成功' : '添加成功')
  } catch (error) {
    ElMessage.error('添加失败')
  }
  paramsData.id || (pageNo.value = 1)
  cancel()
  loading.value = true
  setTimeout(() => {
    getUserList()
  }, 1500)
}
const cancel = () => {
  drawer.value = false
  formRef.value?.resetFields()
  Object.assign(paramsData, {
    username: '',
    name: '',
    password: '',
    id: 0,
  })
}

defineExpose({
  getUserList,
})
</script>
<script lang="ts">
export default {
  name: 'user',
}
</script>
<style lang="scss" scoped></style>
